// 2013-9-8下午03:48:56  net.betou.web.PermistionChoiceDirective.java

package net.betou.web;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import net.betou.trade.entity.main.Role;
import net.betou.trade.main.manager.role.AgencyRoleMng;
import net.betou.trade.web.DBConstants;
import net.betou.web.freemaker.DirectiveUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 1、系统分配了机构和代理商 两个默认角色
 * 2、如果传入的ID，参照机构角色
 * 3、如果传入的ID是代理商，参照代理商角色
 * 4、其他情况都是参照机构的角色（不管是添加还是修改）
 * ------------------------------------------------------------------
 * @author 叶装装
 */
public class PermistionChoiceDirective implements TemplateDirectiveModel{
	/**
	 * 此url必须和perm中url一致。
	 */
	public static final String PARAM_URL = "url";
	
	public static final String PARAM_ID = "id"; // 这个是当前角色的ID
	
	public static final String PARAM_SYSTEM = "system";
	
	
	public static final String PARAM_IDENTITY = "identity";
	
	@SuppressWarnings( "unchecked" )
	public void execute( Environment env, Map params, TemplateModel [ ] loopVars, TemplateDirectiveBody body ) throws TemplateException, IOException {
		String url = DirectiveUtils.getString( PARAM_URL, params );
		Integer id = DirectiveUtils.getInt( PARAM_ID, params );
		Boolean system = DirectiveUtils.getBool( PARAM_SYSTEM, params ); // 如果是系统管理员,则直接显示
		
		String identity = DirectiveUtils.getString( PARAM_IDENTITY, params );
		
		boolean pass = false;
		
		if( system ){
			pass = true;
		}else{
			if( StringUtils.isNotBlank( url )){
				Set< String > perms = getPerms( id,  identity);
				if( perms.contains( url ) ){
					pass = true;
				}
			}
		}

		if( pass ){
			body.render( env.getOut( ) );
		}
	}
	
	private Set< String > getPerms(  Integer id, String identity ){
		
		// 如果当前编辑的角色是机构或者代理商，就参照系统的机构或者代理商的角色
		Role role;
		
		if( DBConstants.DEFINED_AGENCY_IDENTITY.equals( identity )){
			role = manager.findAgencyByDefault( );
		}else if( DBConstants.DEFINED_PROXY_IDENTITY.equals( identity )){
			role = manager.findProxyByDefault( );
		}else{
			role = manager.findById( id );   // 如果当前编辑的角色不是机构或者代理商，就参照当前登录用户的角色
		}
		
		return role.getPerms( );
	}
	
	@Autowired
	private AgencyRoleMng manager;
}
